﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Agro.Library;
using SN.Core;
using Agro.Models;
using Ninject;
using Agro.Services;
using SN.Data;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Agro.Web.Areas.SystemManage.Controllers
{
    public class OrganizationController : BaseController
    {
        [Inject]
        public IOrganizationService OrganizationService { get; set; }

        // GET: /SystemManage/Organization/
        [AuthorizeMenu]
        public ActionResult Organization_Tree()
        {
            ViewBag.pid = CurrUser.UserInfo.User_OrganizationID;
            return View();
        }

        public ActionResult GetTreeNode(string pid, bool withself = false)
        {
            pid = pid ?? "0";
            string sql = string.Format("select organization_id,organization_parentid,organization_name,organization_isdetail from t_organization where organization_parentid='{0}' order by organization_order,organization_id", pid);

            if (withself)//即组织结构树是否包含用户所在级，对非顶级部门有作用，如洛阳市级。
                sql = string.Format("select organization_id,organization_parentid,organization_name,organization_isdetail from t_organization where organization_parentid='{0}' or organization_id='{1}' order by organization_order,organization_id", pid, CurrUser.UserInfo.User_OrganizationID);
            DataTable dataTable = BaseService.DB.FromSql(sql).ToDataTable();
            DataColumn dc = new DataColumn("isParent", typeof(bool));

            if (dataTable.Rows.Count == 0 && string.IsNullOrEmpty(pid))
            {
                //DataRow dr = dataTable.NewRow();
                //dr["organization_id"] = "0";
                //dr["organization_name"] = "单位管理";
                //dr["organization_parentid"] = "-1";
                //dataTable.Rows.InsertAt(dr, 0);
                //dc.DefaultValue = true;
                //dataTable.Columns.Add(dc);
            }
            else
            {
                dc.Expression = "IIF(ORGANIZATION_ISDETAIL=1, true, false)";
                dataTable.Columns.Add(dc);
            }

            string result = JsonConvert.SerializeObject(dataTable, new DataTableConverter());
            return Content(result);


        }


        public ActionResult GetOrganizationList(string organizeId, QueryBase query)
        {
            WhereClip where = WhereClip.All;
            if (!string.IsNullOrEmpty(organizeId))
            {
                where = WhereClip.Bracket(T_Organization._.Organization_ParentID == organizeId ||
                                          T_Organization._.Organization_ID == organizeId);
            }
            else//如果organizeId为空，则什么都不返回。
                return Json("");

            var list = OrganizationService.GetOrganizationList(query, where);
            return JqGrid(list, query);
        }

        public ActionResult Edit(string id, string parentid)
        {
            T_Organization detail = new T_Organization();

            if (string.IsNullOrEmpty(id))
            {
                detail.Organization_ParentID = int.Parse(parentid);
                detail.Organization_Type = "0";
                detail.Organization_Level = "0";
                detail.Organization_IsDetail = "0"; //0为明细 1非明细 
                ViewBag.type = "add";
            }
            else
            {
                detail = BaseService.DB.Single<T_Organization>(T_Organization._.Organization_ID == id);
                
                ViewBag.type = "edit";
            }
            ViewBag.Organization_ParentName = OrganizationService.GetOrganizationName(detail.Organization_ParentID.ToString());
            return View(detail);
        }
        public ActionResult Save(string Organization_ID, FormCollection collection)
        {
            T_Organization Organization = new T_Organization();
            if (Organization.Organization_ID > 0)
            {
                Organization = OrganizationService.GetEntity<T_Organization>(T_Organization._.Organization_ID == Organization_ID);
            }
            else
            {
                Organization.Organization_CreateDate = DateTime.Now.ToString("yyyy-MM-dd");
                Organization.Organization_CreateUserID = CurrUser.UserInfo.User_Name;
            }
            UpdateModel(Organization, collection);
            string msg = string.Empty;
            OrganizationService.SaveOrganization(Organization, out msg);
            return SNJson(Organization.Organization_ID, msg);
        }
        public ActionResult Delete(string id, string pid, int childNum)
        {
            string returnValue = "0";
            returnValue = OrganizationService.DeleteOrganization(id, pid, childNum).ToString();
            return Json(returnValue);
        }

        public ActionResult GetAllOrganizationNodes()
        {
            DataTable dtResult = new DataTable();
            dtResult.Columns.Add("ID", typeof(int));
            dtResult.Columns.Add("PID", typeof(int));
            dtResult.Columns.Add("NAME", typeof(string));
            dtResult.Columns.Add("checked", typeof(bool));
            IList<T_Organization> allOrganizeList = OrganizationService.GetCacheOrganizeList();
            allOrganizeList = allOrganizeList.OrderBy(m => m.Organization_ID).ToList();
            DataRow dr = null;
            foreach (var item in allOrganizeList)
            {
                dr = dtResult.NewRow();
                dr["ID"] = item.Organization_ID;
                dr["PID"] = item.Organization_ParentID;
                dr["NAME"] = item.Organization_Name;
                dr["checked"] = 0;
                dtResult.Rows.Add(dr);
            }
            string result = JsonConvert.SerializeObject(dtResult, new DataTableConverter());
            return Content(result);
        }

        //获取当前部门的所有直接下级。不包括孙级节点。
        public ActionResult GetChildOrganizationNodes()
        {
            DataTable dtResult = new DataTable();
            dtResult.Columns.Add("ID", typeof(int));
            dtResult.Columns.Add("PID", typeof(int));
            dtResult.Columns.Add("NAME", typeof(string));
            dtResult.Columns.Add("checked", typeof(bool));
            IList<T_Organization> allOrganizeList = OrganizationService.GetCacheOrganizeList();
            allOrganizeList = allOrganizeList.OrderBy(m => m.Organization_ID).ToList();
            List<T_Organization> resultList = new List<T_Organization>();
            T_Organization currOrganize = allOrganizeList.FirstOrDefault(m => m.Organization_ID == CurrUser.UserInfo.User_OrganizationID);
            resultList.Add(new T_Organization
            {
                Organization_ID = currOrganize.Organization_ID,
                Organization_ParentID = currOrganize.Organization_ParentID,
                Organization_Name = currOrganize.Organization_Name
            });

            if (currOrganize != null)
            {
                var childList = allOrganizeList.Where(m => m.Organization_ParentID == currOrganize.Organization_ID).ToList();
                foreach (var item in childList)
                {
                    resultList.Add(new T_Organization
                    {
                        Organization_ParentID = item.Organization_ParentID,
                        Organization_ID = item.Organization_ID,
                        Organization_Name = item.Organization_Name
                    });
                    // RecurOrganize(allOrganizeList, resultList, item.Organization_ID);
                }
                DataRow dr = null;
                foreach (var item in resultList)
                {
                    dr = dtResult.NewRow();
                    dr["ID"] = item.Organization_ID;
                    dr["PID"] = item.Organization_ParentID;
                    dr["NAME"] = item.Organization_Name;
                    dr["checked"] = 0;
                    dtResult.Rows.Add(dr);
                }
            }
            string result = JsonConvert.SerializeObject(dtResult, new DataTableConverter());
            return Content(result);
        }

        void RecurOrganize(IList<T_Organization> allOrganizeList, List<T_Organization> resultList, int parentId)
        {
            var list = allOrganizeList.Where(m => m.Organization_ParentID == parentId);
            foreach (var item in list)
            {
                resultList.Add(new T_Organization
                {
                    Organization_ParentID = item.Organization_ParentID,
                    Organization_ID = item.Organization_ID,
                    Organization_Name = item.Organization_Name
                });
                RecurOrganize(allOrganizeList, resultList, item.Organization_ID);
            }
        }


        public ActionResult SelectOrganize()
        {
            ViewBag.GetOrganizeNodesUrl = Url.Content("~/SystemManage/Organization/GetAllOrganizationNodes/");
            return View();
        }

    }
}
